package com.yang.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * zookeeper服务发现相关配置
 *
 * @author yanghongjun19
 * @date 2020/12/27
 **/

@Slf4j
@Configuration
public class ZookeeperClientConfig {

    @Value("${zookeeper.con}")
    private String con;

    @Value("${zookeeper.timeout}")
    private int timeout;

    @Value("${zookeeper.path}")
    private String path;

    private ZooKeeper zk;


    public volatile List<String> servers;

    @Bean
    public ZooKeeper zooKeeper() throws Exception {
        zk = new ZooKeeper(con, timeout, event -> {
            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                try {
                    fetchServerList();
                    zk.addWatch(path, w -> {
                        fetchServerList();
                    }, AddWatchMode.PERSISTENT);
                } catch (Exception e) {
                    log.warn("监听服务节点变化失败:" + e.getMessage());
                }

            }
        });
        return zk;
    }

    /**
     * 获取服务节点
     */
    private void fetchServerList() {
        try {
            List<String> list = zk.getChildren(path, false);
            List<String> temp = new ArrayList<>();
            log.info("服务数量是:" + list.size());
            for (String node : list) {
                byte[] server = zk.getData(path + "/" + node, false, new Stat());
                temp.add(new String(server));
                log.info("服务是:" + new String(server));
            }
            servers = temp;
        } catch (Exception e) {
            log.warn("获取服务节点失败:" + e.getMessage());
        }
    }
}
